#!/usr/bin/python

import sys, getopt, shutil, os, os.path, re
import sr, getoptext, libmvv

def main(argv):
	try:
		argWithOptionals = ["-n", "--number"]
		opts = getoptext.fixOptionalArgs(argWithOptionals, argv[1:])
		print opts
		opts, files = getopt.getopt(opts, "hvqdblus:r:p:a:A:c:n:",
		             ["help", "verbose", "dry-run", "lower-case", "upper-case"
		              "search=", "replace=", "prefix=", "append=", "append-ext=",
		              "number=", "parents", "quiet", "absolute"])
	except getopt.GetoptError, err:
		print str(err)
		sys.exit(2)

	verbose = False
	quiet = False
	dryrun = False
	makeParentDirs = False 
	absolute = False
	chPath = False
	chFile = True
	chExt = False
	cmdMgr = sr.CmdManager()
	for switch, value in opts:
		if switch in ("-h", "--help"):
			printHelp()
			sys.exit(0)
		elif switch in ("-v", "--verbose"):
			verbose = True
		elif switch in ("-q", "--quiet"):
			quiet = True
		elif switch in ("-d", "--dry-run"):
			dryrun = True
		elif switch in ("-b", "--absolute"):
			absolute = True
		elif switch in ("-s", "--search"):
			cmdMgr.add(sr.Search(value))
		elif switch in ("-r", "--replace"):
			cmdMgr.add(sr.Delete())
			cmdMgr.add(sr.Insert(value))
		elif switch in ("-p", "--prefix"):
			cmdMgr.add(sr.Prefix())
			cmdMgr.add(sr.Insert(value))
		elif switch in ("-a", "--append"):
			cmdMgr.add(sr.Append())
			cmdMgr.add(sr.Insert(value))
		elif switch in ("-A", "--append-ext"):
			append = sr.Append()
			append.setAppendExtension(True)
			cmdMgr.add(append)
			cmdMgr.add(sr.Insert(value))
		elif switch in ("-l", "--lower-case"):
			cmdMgr.add(sr.Everything())
			cmdMgr.add(sr.Lowercase())
		elif switch in ("-u", "--upper-case"):
			cmdMgr.add(sr.Everything())
			cmdMgr.add(sr.Uppercase())
		elif switch in ("-n", "--number"):
			start, interval = libmvv.parseNumber(value)
			cmdMgr.append(sr.Numbering(start, interval, sr.Numbering.AFTER))
		elif switch in ("-c", "--change"):
			chPath = False
			chFile = False
			chExt = False
			value = value.lower()
			if value.find("p") > -1:
				chPath = True
			if value.find("f") > -1:
				chFile = True
			if value.find("e") > -1:
				chExt = True
		elif switch in ("--parents"):
			makeParentDirs = True
		else:
			print "Unknown switch: " + switch
			sys.exit(2)
	
	for file in files:
		if absolute:
			file = os.path.abspath(file)
		[path, name, ext] = libmvv.splitFilepath(file)
		if chPath:
			path = cmdMgr.execute(path)
		if chFile:
			name = cmdMgr.execute(name)
		if chExt:
			ext = cmdMgr.execute(ext)
		destFile = libmvv.joinFilePath(path, name, ext)

		newPath = os.path.split(destFile)[0]
		if not os.path.isdir(newPath) and makeParentDirs:
			os.makedirs(newPath)
		if not quiet:
			print file + " => " + destFile
		if not dryrun:
			shutil.move(file, destFile)

def printHelp():
	print "Multi mover: Rename multiple files or folders using general and"
	print "             flexible rules."
	print ""
	print "Usage: mmv [-h] [-v] [-n] [-l] [-u] [-b] [-o pfe] [-s search] [-r replace] [-p prefix]"
	print "           [-a append] [-A apennd-after-ext]"
	print ""
	print "       -h --help  Print this help and exit."
	print "       -v --verbose Print extra output during operation."
	print "       -d --dry-run Do not rename any files. Should be used in"
	print "                    combination with -v."
	print "       -b --absolute If given a relative path, make it absolute"
	print "                    before attempting any manipulation."
	print "       --parent     When operating on both file and path, try to"
	print "                    create non existing dirs (like mkdir --parent)."
	print "                    BE CAREFULL: You can quickly end up with a whole"
	print "                    lot of wird directories! Especially in combination"
	print "                    with --absolute."
	print "       -c --change  [pfe] Give at least one or all of these letters."
	print "                    f is default." 
	print "                    p Change the path part. You might have to use"
	print "                      the --parent switch."
	print "                    f Change the file name. Only giving this is default"
	print "                      on the long term, but current implementation uses pfe."
	print "                    e Change the file extension."
	print ""
	print "String operations:"
	print "       -l --lower-case Make the latest marked text lower case."
	print "       -u --upper-case Make the latest marked text upper case."
	print "       -s --search  Find the given text and mark it. Use e.g."
	print "                    -r to actually replace it."
	print "       -r --replace Replaces the latest marked text with the given"
	print "                    text. Usually the text has been marked using -s."
	print "       -p --prefix  Insert the given string before the treated string."
	print "       -a --append  Append the given string to the treated file name"
	print "                    BUT before the file extension (thus leaving the ext)."
	print "                    Note: This was made before the -c switch, and has not"
	print "                    been changed properly yet."
					#TODO do that.
	print "       -A --append-ext Append the given string to the treated string,"
	print "                    not taking any file extension into account."

# Run the program.
if __name__ == "__main__":
	main(sys.argv)
